<?php

namespace oneStep\Data;

use oneStep\Data\Medoo;

class Connection
{
    public $pdo;
    private static $instance = null;
    public $errorCode;
    public $errorInfo;
    public $statement;


    private function __construct()
    {
    }

    private function __clone()
    {
    }

    public static function Instance()
    {
        if (self::$instance == null) {
            self::$instance = new self();
        }
        return self::$instance->Connection();
    }

    private function Connection()
    {
        $username = config()['username'] ?? null;
        $password = config()['password'] ?? null;
        $dbname   = config()['database_name'];

        $dsn = "mysql:host=localhost;dbname=$dbname;charset=utf8";
        $pdo = new \PDO($dsn, $username, $password);
        $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
        $this->pdo = $pdo;
        return $this;
    }

    /**
     * 云生
     * @param $sql
     * @return mixed
     */
    public function query($sql)
    {
        $data = $this->pdo->query($sql);
        return $data->fetchAll(\PDO::FETCH_ASSOC);
    }

    /**
     * @param $sql
     * @param $map
     * @return mixed
     */
    public function exec($sql, $map)
    {
        $statement = $this->pdo->prepare($sql);
        $i         = 0;
        foreach ($map as $v) {
            $i++;
            $statement->bindValue($i, $v[0], $v[1]);
        }
        $execute         = $statement->execute();
        $this->statement = $statement;
        return $execute;
    }

    /**
     * 获取全部
     * @param $sql
     * @param $map
     * @return mixed
     */
    public function getAll($sql, $map)
    {
        $this->exec($sql, $map);
        $data            = $this->statement->fetchAll(\PDO::FETCH_ASSOC);
        $this->errorCode = $this->statement->errorCode();
        $this->errorInfo = $this->statement->errorInfo();
        return $data;
    }
    /**
     * 获取
     * @param $sql
     * @param $map
     * @return mixed
     */
    public function get($sql, $map)
    {
        $this->exec($sql, $map);
        $data            = $this->statement->fetch(\PDO::FETCH_ASSOC);
        return $data;
    }

    /**
     * 过滤
     * @param $sql
     * @return mixed
     */
    public function quote($sql)
    {
        return $this->pdo->quote($sql);
    }
}